<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Filter&amp;Listener&amp;AJAX | ai_喝可乐's Blog</title><meta name="author" content="AIHCOLA"><meta name="copyright" content="AIHCOLA"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Filter本文摘要：  能够使用 Filter 完成登陆状态校验功能 能够使用 axios 发送 ajax 请求 熟悉 json 格式，并能使用 Fastjson 完成 java 对象和 json 串的相互转换 使用 axios + json 完成综合案例  1.1.Filter概述​		Filter 表示过滤器，是 JavaWeb 三大组件(Servlet、Filter、Listener)之一">
<meta property="og:type" content="article">
<meta property="og:title" content="Filter&amp;Listener&amp;AJAX">
<meta property="og:url" content="https://aihcola.github.io/2023/03/05/Filter&Listener&AJAX/index.html">
<meta property="og:site_name" content="ai_喝可乐&#39;s Blog">
<meta property="og:description" content="Filter本文摘要：  能够使用 Filter 完成登陆状态校验功能 能够使用 axios 发送 ajax 请求 熟悉 json 格式，并能使用 Fastjson 完成 java 对象和 json 串的相互转换 使用 axios + json 完成综合案例  1.1.Filter概述​		Filter 表示过滤器，是 JavaWeb 三大组件(Servlet、Filter、Listener)之一">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picsum.photos/seed/d/3456/2304">
<meta property="article:published_time" content="2023-03-05T12:48:48.754Z">
<meta property="article:modified_time" content="2023-05-06T05:49:46.994Z">
<meta property="article:author" content="AIHCOLA">
<meta property="article:tag" content="JavaWeb">
<meta property="article:tag" content="JavaEE">
<meta property="article:tag" content="Filter">
<meta property="article:tag" content="Listener">
<meta property="article:tag" content="AJAX">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picsum.photos/seed/d/3456/2304"><link rel="shortcut icon" href="/img/dog.jpeg"><link rel="canonical" href="https://aihcola.github.io/2023/03/05/Filter&amp;Listener&amp;AJAX/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Filter&Listener&AJAX',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-05-06 13:49:46'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/mycss.css"><meta name="generator" content="Hexo 6.3.0"></head><body><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pace-js/themes/blue/pace-theme-minimal.min.css"/><script src="https://cdn.jsdelivr.net/npm/pace-js/pace.min.js"></script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/dog.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">4</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">8</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-book"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/timeline/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://picsum.photos/seed/sunshine/4912/3264')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">ai_喝可乐's Blog</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-book"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/timeline/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Filter&amp;Listener&amp;AJAX</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-03-05T12:48:48.754Z" title="发表于 2023-03-05 20:48:48">2023-03-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-05-06T05:49:46.994Z" title="更新于 2023-05-06 13:49:46">2023-05-06</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%BF%87%E6%BB%A4%E5%99%A8/">过滤器</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%BF%87%E6%BB%A4%E5%99%A8/%E4%B8%89%E5%A4%A7%E7%BB%84%E4%BB%B6/">三大组件</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%BF%87%E6%BB%A4%E5%99%A8/%E4%B8%89%E5%A4%A7%E7%BB%84%E4%BB%B6/Javaweb/">Javaweb</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Filter&amp;Listener&amp;AJAX"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Filter"><a href="#Filter" class="headerlink" title="Filter"></a><strong>Filter</strong></h1><p><strong>本文摘要：</strong></p>
<ul>
<li>能够使用 <strong>Filter</strong> 完成登陆状态校验功能</li>
<li>能够使用 <strong>axios</strong> 发送 <strong>ajax</strong> 请求</li>
<li>熟悉 <strong>json</strong> 格式，并能使用 <strong>Fastjson</strong> 完成 <strong>java</strong> 对象和 <strong>json</strong> 串的相互转换</li>
<li>使用 <strong>axios</strong> <strong>+</strong> <strong>json</strong> 完成综合案例</li>
</ul>
<h2 id="1-1-Filter概述"><a href="#1-1-Filter概述" class="headerlink" title="1.1.Filter概述"></a>1.1.Filter概述</h2><p>​		Filter 表示过滤器，是 JavaWeb 三大组件(Servlet、Filter、Listener)之一。我们之前都已经学习过了Servlet ，现在我们来学习Filter和Listener。</p>
<p>过滤器可以把对资源的请求<code>拦截</code>下来，从而实现一些特殊的功能。</p>
<p>例如某些网站未登录不能查看评论，不能将商品加入购物车，得把你拦下来，先让你登录，也就是在访问前，先经过Filter。</p>
<p>下面来具体说说，拦截器拦截到后可以做什么功能呢？</p>
<p>过滤器一般完成一些通用的操作。比如每个资源都要写一些代码完成某个功能，我们总不能在每个资源中写这样的代码吧，而此时我们可以将这些代码写在过滤器中，因为请求每一个资源都要经过过滤器。</p>
<p>我们之前做的品牌数据管理的案例中就已经做了登陆的功能，但这个登录功能其实是如同虚设的，我们可以直接访问登录后的页面，所以本文的目标就是完善登录功能，不登录就无法查看数据。</p>
<h2 id="1-2-Filter入门"><a href="#1-2-Filter入门" class="headerlink" title="1.2.Filter入门"></a>1.2.Filter入门</h2><h3 id="1-2-1开发步骤"><a href="#1-2-1开发步骤" class="headerlink" title="1.2.1开发步骤"></a>1.2.1开发步骤</h3><p>​		进行<code>Filter</code>开发分为以下三步实现</p>
<p>​		1.定义类，实现Filter接口，并重写其所有方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//实现Filter接口，重写所有方法</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FilterDemo1</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​		2.配置Filter拦截路径资源：在类上定义<code>@WebFilter</code>注解。而注解的value属性			值<code>/*</code>表示拦截所有资源</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//这里暂时先拦截所有资源，后面我们会仔细讲拦截路径的配置</span></span><br><span class="line"><span class="meta">@WebFilter(&quot;/*&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FilterDemo1</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-2-1代码演示"><a href="#1-2-1代码演示" class="headerlink" title="1.2.1代码演示"></a>1.2.1代码演示</h3><ul>
<li>创建一个web项目，在<code>webapp</code>下创建<code>hello.jsp</code>页面</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">&lt;%@ page contentType=&quot;text/html;charset=UTF-8&quot; language=&quot;java&quot; %&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--随便输出点什么东西--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>HELLO FILTER<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>pom.xml配置如下</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span> <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">  <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.example<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>filter-demo<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">packaging</span>&gt;</span>war<span class="tag">&lt;/<span class="name">packaging</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">name</span>&gt;</span>filter-demo Maven Webapp<span class="tag">&lt;/<span class="name">name</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">url</span>&gt;</span>http://maven.apache.org<span class="tag">&lt;/<span class="name">url</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.8.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mortbay.jetty<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.5-20081211<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.1.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">scope</span>&gt;</span>compile<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">build</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">finalName</span>&gt;</span>filter-demo<span class="tag">&lt;/<span class="name">finalName</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">build</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>在java目录下新建<code>com.blog.web.filter</code>包，并新建<code>FilterDemo1</code>类</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebFilter(&quot;/*&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FilterDemo1</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;doFilter...&quot;</span>);</span><br><span class="line">        filterChain.doFilter(servletRequest, servletResponse);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>测试<ul>
<li>将放行的代码注释掉，我们访问<code>hello.jsp</code>页面，不会有任何内容，因为被拦截了，且没有放行，控制台会输出<code>doFilter...</code></li>
<li>打开放行的代码，我们访问<code>hello.jsp</code>页面，会有h1标签正常输出<code>HELLO FILTER</code></li>
</ul>
</li>
</ul>
<p>​		上述效果说明了FilterDemo1这个过滤器的<code>doFilter</code>方法被执行了，且必须添加放行的方法才能访问<code>hello.jsp</code>页面</p>
<h2 id="1-3-Filter执行流程"><a href="#1-3-Filter执行流程" class="headerlink" title="1.3.Filter执行流程"></a>1.3.Filter执行流程</h2><p>​																																									<img src= "" data-lazy-src="https://s2.loli.net/2022/08/21/ghQFMEkt1R4eJ38.png" alt="Filter执行流程.png" style="zoom: 67%;" /></p>
<p><strong>如上图</strong>是使用过滤器的流程，我们通过以下问题来研究过滤器的执行流程：</p>
<ul>
<li>放行后访问对应资源，资源访问完成后，还会回到Filter中吗？<ul>
<li>从上图就可以看出肯定会回到Filter中</li>
</ul>
</li>
<li>如果回到Filter中，是重头执行还是执行放行后的逻辑呢？<ul>
<li>如果是重头执行的话，就意味着 <code>放行前逻辑</code> 会被执行两次，肯定不会这样设计了；所以访问完资源后，会回到 <code>放行后逻辑</code>，执行该部分代码。</li>
</ul>
</li>
</ul>
<p>通过上述的说明，我们可以总结一下Filter的执行流程</p>
<ul>
<li>执行放行前逻辑 —&gt; 放行 —&gt; 访问资源 —&gt; 执行放行后逻辑</li>
</ul>
<p>1.接下来我们通过代码验证一下，在 <code>doFilter()</code> 方法前后都加上输出语句</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;1.Filter...&quot;</span>);</span><br><span class="line">    filterChain.doFilter(servletRequest, servletResponse);</span><br><span class="line">    System.out.println(<span class="string">&quot;3.Filter...&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2.在<code>hello.jsp</code>中添加输出语句如下</p>
<figure class="highlight jsp"><table><tr><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">&lt;h1&gt;HELLO FILTER&lt;/h1&gt;</span><br><span class="line">&lt;%</span><br><span class="line">    System.out.println(<span class="string">&quot;2.Filter...&quot;</span>);</span><br><span class="line">%&gt;</span><br><span class="line">&lt;/body&gt;</span><br></pre></td></tr></table></figure>

<p>3.重启服务器，访问<code>hello.jsp</code>页面，控制台输出结果如下，符合我们的预期结果</p>
<blockquote>
<p>​	1.Filter…<br>​	2.Filter…<br>​	3.Filter…</p>
</blockquote>
<h2 id="1-4-Filter拦截路径配置"><a href="#1-4-Filter拦截路径配置" class="headerlink" title="1.4.Filter拦截路径配置"></a>1.4.Filter拦截路径配置</h2><p>​		拦截路径表示 Filter 会对请求的哪些资源进行拦截，使用 <code>@WebFilter</code> 注解进行配置。如：<code>@WebFilter(&quot;拦截路径&quot;)</code></p>
<p>​		拦截路径有如下四种配置方式：</p>
<ul>
<li>拦截具体的资源：&#x2F;index.jsp：只有访问index.jsp时才会被拦截</li>
<li>目录拦截：&#x2F;user&#x2F;*：访问&#x2F;user下的所有资源，都会被拦截</li>
<li>后缀名拦截：*.jsp：访问后缀名为jsp的资源，都会被拦截</li>
<li>拦截所有：&#x2F;*：访问所有资源，都会被拦截</li>
</ul>
<h2 id="1-5-过滤器链"><a href="#1-5-过滤器链" class="headerlink" title="1.5.过滤器链"></a>1.5.过滤器链</h2><h3 id="1-5-1-概述"><a href="#1-5-1-概述" class="headerlink" title="1.5.1.概述"></a>1.5.1.概述</h3><p>​					过滤器链是指在一个Web应用，可以配置多个过滤器，这多个过滤器称为过滤器链。</p>
<p>​					如下图就是一个过滤器链，我们学习过滤器链主要是学习过滤器链执行的流程</p>
<p><img src= "" data-lazy-src="https://s2.loli.net/2022/08/21/G4pqy53IAmBdDoC.png" alt="过滤器链.png"></p>
<p>​		上图中的过滤器链执行是按照以下流程执行：</p>
<ol>
<li>执行 <code>Filter1</code> 的放行前逻辑代码</li>
<li>执行 <code>Filter1</code> 的放行代码</li>
<li>执行 <code>Filter2</code> 的放行前逻辑代码</li>
<li>执行 <code>Filter2</code> 的放行代码</li>
<li>访问到资源</li>
<li>执行 <code>Filter2</code> 的放行后逻辑代码</li>
<li>执行 <code>Filter1</code> 的放行后逻辑代码</li>
</ol>
<p>​		以上流程串起来就像一条链子，故称之为过滤器链。</p>
<h3 id="1-5-2-代码演示"><a href="#1-5-2-代码演示" class="headerlink" title="1.5.2.代码演示"></a>1.5.2.代码演示</h3><p>​					我们在<code>com.blog.web.filter</code>包下再新建一个<code>FilterDemo2</code>类，并实现Filter接口，重写其所有方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebFilter(&quot;/*&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FilterDemo2</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;2.Filter...&quot;</span>);</span><br><span class="line">        filterChain.doFilter(servletRequest, servletResponse);</span><br><span class="line">        System.out.println(<span class="string">&quot;4.Filter...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​				修改<code>FilterDemo1</code>类的<code>doFilter</code>方法，将输出语句调成我们预期的结果，最终测试的时候，看看是否符合预期</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;1.Filter...&quot;</span>);</span><br><span class="line">    filterChain.doFilter(servletRequest, servletResponse);</span><br><span class="line">    System.out.println(<span class="string">&quot;5.Filter...&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​				修改<code>hello.jsp</code>，将输出语句改为预期结果</p>
<figure class="highlight jsp"><table><tr><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">&lt;h1&gt;HELLO FILTER&lt;/h1&gt;</span><br><span class="line">&lt;%</span><br><span class="line">    System.out.println(<span class="string">&quot;3.Filter...&quot;</span>);</span><br><span class="line">%&gt;</span><br><span class="line">&lt;/body&gt;</span><br></pre></td></tr></table></figure>

<p>​			重启服务器，访问<code>hello.jsp</code>页面，控制台输出如下，符合我们预期的结果</p>
<p><img src= "" data-lazy-src="C:\Users\20823\AppData\Roaming\Typora\typora-user-images\image-20230118215028014.png" alt="image-20230118215028014"></p>
<h3 id="1-5-3-问题"><a href="#1-5-3-问题" class="headerlink" title="1.5.3.问题"></a>1.5.3.问题</h3><p>​					上面代码中为什么是先执行 <code>FilterDemo</code> ，后执行 <code>FilterDemo2</code> 呢？</p>
<figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line">- 我们现在使用的是注解配置<span class="title class_">Filter</span>，而这种配置方式的优先级是按照过滤器类名(字符串)的自然排序。</span><br><span class="line">- 比如有如下两个名称的过滤器 ： <span class="string">`BFilterDemo`</span> 和 <span class="string">`AFilterDemo`</span> 。那一定是 <span class="string">`AFilterDemo`</span> 过滤器先执行。</span><br></pre></td></tr></table></figure>

<h2 id="1-6-案例"><a href="#1-6-案例" class="headerlink" title="1.6.案例"></a>1.6.案例</h2><h3 id="1-6-1-需求"><a href="#1-6-1-需求" class="headerlink" title="1.6.1.需求"></a>1.6.1.需求</h3><p>​						访问服务器资源时，需要先进行登录验证，如果没有登录，则自动跳转到登录页面</p>
<h3 id="1-6-2-分析"><a href="#1-6-2-分析" class="headerlink" title="1.6.2.分析"></a>1.6.2.分析</h3><p>​					要是搁以前，我们要实现该功能可能得在每一个资源里加入登陆状态校验的代码<br>​					但现在，只需要写一个 <code>Filter</code> ，在该过滤器中进行登陆状态校验即可。而在该 <code>Filter</code> 中逻辑如下：</p>
<ul>
<li>判断访问的是否为登录之后才能看的资源<ul>
<li>是：放行</li>
<li>不是：进行登录验证</li>
</ul>
</li>
<li>判断用户是否登录：Session中是否有user对象<ul>
<li>登录：放行</li>
<li>未登录：跳转至登录页面，并给出提示信息</li>
</ul>
</li>
</ul>
<h3 id="1-6-3-代码实现"><a href="#1-6-3-代码实现" class="headerlink" title="1.6.3.代码实现"></a>1.6.3.代码实现</h3><h4 id="1-6-3-1-创建Filter"><a href="#1-6-3-1-创建Filter" class="headerlink" title="1.6.3.1.创建Filter"></a>1.6.3.1.创建Filter</h4><p>​								在 <code>brand-demo</code> 工程创建 <code>com.itheima.web.filter</code> 包，在该下创建名为 <code>LoginFilter</code> 的过滤器</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebFilter(&quot;/*&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LoginFilter</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain chain)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">      </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig config)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-6-3-2-编写逻辑代码"><a href="#1-6-3-2-编写逻辑代码" class="headerlink" title="1.6.3.2.编写逻辑代码"></a>1.6.3.2.编写逻辑代码</h4><p>​								在 <code>doFilter()</code> 方法中编写登陆状态校验的逻辑代码。</p>
<p>​								我们首先需要从 <code>session</code> 对象中获取用户信息，但是 <code>ServletRequest</code> 类型的 requset 对象没有获取 								session 对象的方法，所以此时需要将 request对象强转成 <code>HttpServletRequest</code> 对象。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebFilter(&quot;/*&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LoginFilter</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain chain)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="comment">//强转操作</span></span><br><span class="line">        <span class="type">HttpServletRequest</span> <span class="variable">httpRequest</span> <span class="operator">=</span> (HttpServletRequest) request;</span><br><span class="line">        <span class="type">HttpSession</span> <span class="variable">session</span> <span class="operator">=</span> httpRequest.getSession();</span><br><span class="line">        <span class="comment">//获取是否有user对象</span></span><br><span class="line">        <span class="type">Object</span> <span class="variable">user</span> <span class="operator">=</span> session.getAttribute(<span class="string">&quot;user&quot;</span>);</span><br><span class="line">        <span class="comment">//如果有user对象，那么就是已登录状态，直接放行</span></span><br><span class="line">        <span class="keyword">if</span> (user != <span class="literal">null</span>) &#123;</span><br><span class="line">            chain.doFilter(request, response);</span><br><span class="line">        <span class="comment">//如果没有user对象，那就是未登录，不允许访问，给出错误信息并跳转到登录页面</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            httpRequest.setAttribute(<span class="string">&quot;login_msg&quot;</span>, <span class="string">&quot;您尚未登录&quot;</span>);</span><br><span class="line">            httpRequest.getRequestDispatcher(<span class="string">&quot;/login.jsp&quot;</span>).forward(request, response);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig config)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-6-3-3-测试并抛出问题"><a href="#1-6-3-3-测试并抛出问题" class="headerlink" title="1.6.3.3.测试并抛出问题"></a>1.6.3.3.测试并抛出问题</h4><p>​								重启服务器，访问<code>register.jsp</code>注册页面，竟然访问不了了，也是直接跳转到了登录页面，而且如果你								配置了css文件，css样式也显示不出来了，这是怎么回事呢？</p>
<h4 id="1-6-3-4-问题分析及解决"><a href="#1-6-3-4-问题分析及解决" class="headerlink" title="1.6.3.4.问题分析及解决"></a>1.6.3.4.问题分析及解决</h4><p>​							因为我们配置的是对所有页面进行拦截，但现在需要对所有的登陆和注册相关的资源进行放行。</p>
<p>​							所以我们需要在判断session中是否包含用户信息之前，应该加上对登陆及注册相关资源放行的逻辑处理</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">HttpServletRequest</span> <span class="variable">httpRequest</span> <span class="operator">=</span> (HttpServletRequest) request;</span><br><span class="line"><span class="comment">//在数组中存储注册和登录相关的资源路径</span></span><br><span class="line">String[] urls = &#123;<span class="string">&quot;/login.jsp&quot;</span>,<span class="string">&quot;/register.jsp&quot;</span>,<span class="string">&quot;/checkCodeServlet&quot;</span>,<span class="string">&quot;/registerServlet&quot;</span>,<span class="string">&quot;/loginServlet&quot;</span>&#125;;</span><br><span class="line"><span class="comment">//获取当前的访问路径</span></span><br><span class="line"><span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> httpRequest.getRequestURL().toString();</span><br><span class="line"><span class="comment">//遍历数组</span></span><br><span class="line"><span class="keyword">for</span> (String u : urls) &#123;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串</span></span><br><span class="line"><span class="comment">        比如当前访问的资源路径是  /brand-demo/login.jsp</span></span><br><span class="line"><span class="comment">        而字符串 /brand-demo/login.jsp 包含了字符串 /login.jsp ，所以这个字符串就需要放行</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="keyword">if</span> (url.contains(u))&#123;</span><br><span class="line">        <span class="comment">//找到了就放行</span></span><br><span class="line">        chain.doFilter(request,response);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-6-3-5-过滤器完整代码"><a href="#1-6-3-5-过滤器完整代码" class="headerlink" title="1.6.3.5.过滤器完整代码"></a>1.6.3.5.过滤器完整代码</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebFilter(&quot;/*&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LoginFilter</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain chain)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="type">HttpServletRequest</span> <span class="variable">httpRequest</span> <span class="operator">=</span> (HttpServletRequest) request;</span><br><span class="line">        String[] urls = &#123;<span class="string">&quot;/login.jsp&quot;</span>,<span class="string">&quot;/register.jsp&quot;</span>,<span class="string">&quot;/checkCodeServlet&quot;</span>,<span class="string">&quot;/registerServlet&quot;</span>,<span class="string">&quot;/loginServlet&quot;</span>&#125;;</span><br><span class="line">        <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> httpRequest.getRequestURL().toString();</span><br><span class="line">        <span class="keyword">for</span> (String u : urls) &#123;</span><br><span class="line">            <span class="keyword">if</span> (url.contains(u))&#123;</span><br><span class="line">                chain.doFilter(request,response);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">HttpSession</span> <span class="variable">session</span> <span class="operator">=</span> httpRequest.getSession();</span><br><span class="line">        <span class="type">Object</span> <span class="variable">user</span> <span class="operator">=</span> session.getAttribute(<span class="string">&quot;user&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (user != <span class="literal">null</span>) &#123;</span><br><span class="line">            chain.doFilter(request, response);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            httpRequest.setAttribute(<span class="string">&quot;login_msg&quot;</span>, <span class="string">&quot;您尚未登录&quot;</span>);</span><br><span class="line">            httpRequest.getRequestDispatcher(<span class="string">&quot;/login.jsp&quot;</span>).forward(request, response);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig config)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







<h1 id="Listener"><a href="#Listener" class="headerlink" title="Listener"></a>Listener</h1><h2 id="2-1概述"><a href="#2-1概述" class="headerlink" title="2.1概述"></a>2.1概述</h2><ul>
<li><p>Listener 表示监听器，是 JavaWeb 三大组件(Servlet、Filter、Listener)之一。</p>
</li>
<li><p>监听器可以监听就是在 <code>application</code>，<code>session</code>，<code>request</code> 三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。</p>
<p>request 和 session 我们学习过。而 <code>application</code> 是 <code>ServletContext</code> 类型的对象。</p>
<p><code>ServletContext</code> 代表整个web应用，在服务器启动的时候，tomcat会自动创建该对象。在服务器关闭时会自动销毁该对象。</p>
</li>
</ul>
<h2 id="2-2分类"><a href="#2-2分类" class="headerlink" title="2.2分类"></a>2.2分类</h2><p>​	JavaWeb 提供了8个监听器：</p>
<table>
<thead>
<tr>
<th align="center">监听器分类</th>
<th align="center">监听器名称</th>
<th align="center">作用</th>
</tr>
</thead>
<tbody><tr>
<td align="center">servletContext监听</td>
<td align="center">servletContextListener</td>
<td align="center">用于对ServletContext对象进行监听(创建、销毁)</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">ServletContextAttributeListener</td>
<td align="center">对ServletContext对象中属性的监听（增删改属性）</td>
</tr>
<tr>
<td align="center">session监听</td>
<td align="center">HttpSessionListener</td>
<td align="center">对Session对象的整体状态的监听（创建、销毁)</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">HttpSessionAttributeListener</td>
<td align="center">对Session对象中的属性监听(增删改属性)</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">HttpSessionBindingListener</td>
<td align="center">监听对象于Session的绑定和解除</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">HttpsessionActivationListener</td>
<td align="center">对Session数据的钝化和活化的监听</td>
</tr>
<tr>
<td align="center">Request监听</td>
<td align="center">servletRequestListener</td>
<td align="center">对Request对象进行监听(创建、销毁)</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">servletRequestAttributeListener</td>
<td align="center">对Request对象中属性的监听(增删改属性)</td>
</tr>
</tbody></table>
<p>这里面只有 <code>ServletContextListener</code> 这个监听器后期我们会接触到，<code>ServletContextListener</code> 是用来监听 <code>ServletContext</code> 对象的创建和销毁。</p>
<p><code>ServletContextListener</code> 接口中有以下两个方法</p>
<ul>
<li><code>void contextInitialized(ServletContextEvent sce)</code>：<code>ServletContext</code> 对象被创建了会自动执行的方法</li>
<li><code>void contextDestroyed(ServletContextEvent sce)</code>：<code>ServletContext</code> 对象被销毁时会自动执行的方法</li>
</ul>
<h2 id="2-3代码演示"><a href="#2-3代码演示" class="headerlink" title="2.3代码演示"></a>2.3代码演示</h2><p>​	我们只演示一下 <code>ServletContextListener</code> 监听器</p>
<ul>
<li>定义一个类，实现<code>ServletContextListener</code> 接口</li>
<li>重写所有的抽象方法</li>
<li>使用 <code>@WebListener</code> 进行配置</li>
</ul>
<p>​	代码如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebListener</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ContextLoaderListener</span> <span class="keyword">implements</span> <span class="title class_">ServletContextListener</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">contextInitialized</span><span class="params">(ServletContextEvent sce)</span> &#123;</span><br><span class="line">        <span class="comment">//加载资源</span></span><br><span class="line">        System.out.println(<span class="string">&quot;ContextLoaderListener...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">contextDestroyed</span><span class="params">(ServletContextEvent sce)</span> &#123;</span><br><span class="line">        <span class="comment">//释放资源</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	启动服务器，就可以在控制台输出了 <code>ContextLoaderListener...</code>，同时也说明	了 <code>ServletContext</code> 对象在服务器启动的时候被创建了。</p>
<h1 id="AJAX"><a href="#AJAX" class="headerlink" title="AJAX"></a>AJAX</h1><h2 id="3-1概述"><a href="#3-1概述" class="headerlink" title="3.1概述"></a>3.1概述</h2><p>​	<code>AJAX</code> (Asynchronous JavaScript And XML)：异步的 JavaScript 和 XML。</p>
<h3 id="3-1-1-作用"><a href="#3-1-1-作用" class="headerlink" title="3.1.1.作用"></a>3.1.1.作用</h3><p>​		AJAX 作用有以下两方面：</p>
<ol>
<li>与服务器进行数据交换：通过AJAX可以给服务器发送请求，服务器将数据直接响应回给浏览器。<ul>
<li>在之前，我们做功能的流程是，<code>Servlet</code> 调用完业务逻辑层，然后将数据存储到域对象中，然后跳转到指定的 <code>jsp</code> 页面，在页面上使用 <code>EL表达式</code> 和 <code>JSTL</code> 标签库进行数据的展示。</li>
<li>而我们学习了AJAX 后，就可以使用AJAX和服务器进行通信，以达到<code>使用HTML+AJAX来替换JSP页面</code>了。浏览器发送请求servlet，servlet 调用完业务逻辑层后将数据直接响应回给浏览器页面，页面使用 HTML 来进行数据展示。</li>
</ul>
</li>
<li>异步交互：可以在不重新加载整个页面的情况下，与服务器交换数据并更新部分网页的技术，如：搜索联想、用户名是否可用校验，等等…<ul>
<li>当我们在百度输入一些关键字（例如 <code>奥运</code>）后就会在下面联想出相关的内容，而联想出来的这部分数据肯定是存储在百度的服务器上，而我们并没有看出页面重新刷新，这就是<code>更新局部页面</code>的效果。</li>
<li>我们在用户名的输入框输入用户名，当输入框一失去焦点，如果用户名已经被占用就会在下方展示提示的信息；在这整个过程中也没有页面的刷新，只是在局部展示出了提示信息，这就是<code>更新局部页面</code>的效果。</li>
</ul>
</li>
</ol>
<h3 id="3-1-2-同步与异步"><a href="#3-1-2-同步与异步" class="headerlink" title="3.1.2.同步与异步"></a>3.1.2.同步与异步</h3><p>​		知道了局部刷新后，接下来我们再聊聊同步和异步:</p>
<p>​		同步发送请求过程如下<img src= "" data-lazy-src="https://s2.loli.net/2022/08/22/Oli3K2nHIhNdBGr.png" alt="同步请求.png"></p>
<p>​		浏览器页面在发送请求给服务器，在服务器处理请求的过程中，浏览器页面不能做其他的操作。只能等到服务器响应结束后才能，浏览器页面才能继续做其他的操作。</p>
<p>​		异步发送请求过程如下<img src= "" data-lazy-src="https://s2.loli.net/2022/08/22/upkrYOq3JSmyAf2.png" alt="异步请求.png"></p>
<p>​		浏览器页面发送请求给服务器，在服务器处理请求的过程中，浏览器页面还可以做其他的操作。</p>
<blockquote>
<p>​		2022-09-22复盘补充：<br>所谓异步，就是主程序一直往下走，延迟和等待程序放在另一个列表中等待执行，不阻塞主程序继续往下进行<br>JS中大部分都是同步，少数的异步有以下几个</p>
<ul>
<li>定时器settimeout和steInterval</li>
<li>ajax异步请求</li>
<li>promise</li>
<li>……</li>
</ul>
<p>异步的好处是：它不会因为延时和等待阻塞程序<br>但异步存在一些问题，例如原计划从1到4执行</p>
<ol>
<li>挂加速器</li>
<li>打开steam</li>
<li>上号</li>
<li>打派派</li>
</ol>
<p>但现在3是异步操作，结果变成1243，没登录账号，你打个锤子的派派</p>
</blockquote>
<h2 id="3-2快速入门"><a href="#3-2快速入门" class="headerlink" title="3.2快速入门"></a>3.2快速入门</h2><p>​		创建一个<code>ajax-demo</code>的web项目，并导入servlet的坐标</p>
<h3 id="3-2-1-服务端实现"><a href="#3-2-1-服务端实现" class="headerlink" title="3.2.1.服务端实现"></a>3.2.1.服务端实现</h3><p>​			在项目的java目录下创建 <code>com.itheima.blog.servlet</code>包，并在该包下创建名为 <code>AjaxServlet</code> 的servlet</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebServlet(&quot;/ajaxServlet&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AjaxServlet</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        response.getWriter().write(<span class="string">&quot;HELLO AJAX&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doPost</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="built_in">this</span>.doGet(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-2-2-客户端实现"><a href="#3-2-2-客户端实现" class="headerlink" title="3.2.2.客户端实现"></a>3.2.2.客户端实现</h3><p>​	在 <code>webapp</code> 下创建名为 <code>01-ajax-demo1.html</code> 的页面，在该页面书写 <code>ajax</code> 代码</p>
<p>​	创建核心对象，不同的浏览器创建的对象是不同的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> <span class="keyword">var</span> xhttp;</span><br><span class="line"><span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">XMLHttpRequest</span>) &#123;</span><br><span class="line">    xhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// code for IE6, IE5</span></span><br><span class="line">    xhttp = <span class="keyword">new</span> <span class="title class_">ActiveXObject</span>(<span class="string">&quot;Microsoft.XMLHTTP&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	发送请求</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//建立连接，这里要写全地址，因为在后期，前端的代码和后端的代码并不是部署在同一个服务器上</span></span><br><span class="line">xhttp.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, <span class="string">&quot;http://localhost:8080/ajax_demo/ajaxServlet&quot;</span>);</span><br><span class="line"><span class="comment">//发送请求</span></span><br><span class="line">xhttp.<span class="title function_">send</span>();</span><br></pre></td></tr></table></figure>

<p>​	获取响应</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">xhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; <span class="variable language_">this</span>.<span class="property">status</span> == <span class="number">200</span>) &#123;</span><br><span class="line">        <span class="comment">// 通过 this.responseText 可以获取到服务端响应的数据</span></span><br><span class="line">        <span class="title function_">alert</span>(<span class="variable language_">this</span>.<span class="property">responseText</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>​	完整代码如下：</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">  <span class="keyword">var</span> xhttp;</span></span><br><span class="line"><span class="language-javascript">  <span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">XMLHttpRequest</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">    xhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span></span><br><span class="line"><span class="language-javascript">  &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// code for IE6, IE5</span></span></span><br><span class="line"><span class="language-javascript">    xhttp = <span class="keyword">new</span> <span class="title class_">ActiveXObject</span>(<span class="string">&quot;Microsoft.XMLHTTP&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">  &#125;</span></span><br><span class="line"><span class="language-javascript">  <span class="comment">//建立连接</span></span></span><br><span class="line"><span class="language-javascript">  xhttp.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, <span class="string">&quot;http://localhost:8080/ajax_demo/ajaxServlet&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">  <span class="comment">//发送请求</span></span></span><br><span class="line"><span class="language-javascript">  xhttp.<span class="title function_">send</span>();</span></span><br><span class="line"><span class="language-javascript">  xhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; <span class="variable language_">this</span>.<span class="property">status</span> == <span class="number">200</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">      <span class="comment">// 通过 this.responseText 可以获取到服务端响应的数据</span></span></span><br><span class="line"><span class="language-javascript">      <span class="title function_">alert</span>(<span class="variable language_">this</span>.<span class="property">responseText</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript">  &#125;;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-2-3-测试"><a href="#3-2-3-测试" class="headerlink" title="3.2.3.测试"></a>3.2.3.测试</h3><p>​			在浏览器地址栏输入 <code>http://localhost:8080/ajax-demo/01-ajax-demo1.html</code> ，在 <code>01-ajax-demo1.html</code>加载的时候就会发送 <code>ajax</code> 请求，并有一个alert弹窗输出<code>HELLO AJAX</code></p>
<h2 id="3-3案例"><a href="#3-3案例" class="headerlink" title="3.3案例"></a>3.3案例</h2><p>​	需求：在完成用户注册时，当用户名输入框失去焦点时，校验用户名是否在数据库已存在</p>
<h3 id="3-3-1-分析"><a href="#3-3-1-分析" class="headerlink" title="3.3.1.分析"></a>3.3.1.分析</h3><ul>
<li>前端完成的逻辑<ol>
<li>给用户名输入框绑定光标失去焦点事件 <code>onblur</code></li>
<li>发送 ajax请求，携带username参数</li>
<li>处理响应：是否显示提示信息</li>
</ol>
</li>
<li>后端完成的逻辑<ol>
<li>接收用户名</li>
<li>调用service查询User。此案例是为了演示前后端异步交互，所以此处我们不做业务逻辑处理</li>
<li>返回标记</li>
</ol>
</li>
</ul>
<h3 id="3-3-2-后端实现"><a href="#3-3-2-后端实现" class="headerlink" title="3.3.2.后端实现"></a>3.3.2.后端实现</h3><p>​			在 <code>com.blog.web.servlet</code> 包中定义名为 <code>SelectUserServlet</code> 的servlet。代码如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebServlet(&quot;/selectUserServlet&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SelectUserServlet</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="comment">//接收用户名</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">username</span> <span class="operator">=</span> request.getParameter(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        <span class="comment">//2. 调用service查询User对象，此处不进行业务逻辑处理，直接给 flag 赋值为 true，表明用户名占用</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">        <span class="comment">//响应标记</span></span><br><span class="line">        response.getWriter().write(<span class="string">&quot;&quot;</span> + flag);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doPost</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="built_in">this</span>.doGet(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-3-3-前端实现"><a href="#3-3-3-前端实现" class="headerlink" title="3.3.3.前端实现"></a>3.3.3.前端实现</h3><p>​			随便写一个注册的页面<code>register.html</code></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;utf-8&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/ajax_demo/selectUserServlet&quot;</span> <span class="attr">method</span>=<span class="string">&quot;get&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>欢迎注册<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">    用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">id</span>=<span class="string">&quot;username&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span> <span class="attr">id</span>=<span class="string">&quot;username_arr&quot;</span> <span class="attr">style</span>=<span class="string">&quot;display:none;&quot;</span>&gt;</span>用户名已被占用<span class="tag">&lt;/<span class="name">span</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    密码：<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">value</span>=<span class="string">&quot;注册&quot;</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​			然后给用户名输入框绑定光标失去焦点事件 <code>onblur</code></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;username&quot;</span>).<span class="property">onblur</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​			发送 ajax请求，携带username参数</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 发送ajax请求</span></span><br><span class="line"><span class="comment">// 获取用户名</span></span><br><span class="line"><span class="keyword">var</span> username = <span class="variable language_">this</span>.<span class="property">value</span>;  </span><br><span class="line"><span class="keyword">var</span> xhttp;  </span><br><span class="line"><span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">XMLHttpRequest</span>) &#123;</span><br><span class="line">    xhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// code for IE6, IE5</span></span><br><span class="line">    xhttp = <span class="keyword">new</span> <span class="title class_">ActiveXObject</span>(<span class="string">&quot;Microsoft.XMLHTTP&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 发送请求，由于我们发送的是 GET 请求，所以需要在 URL 后拼接从输入框获取的用户名数据。</span></span><br><span class="line">xhttp.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, <span class="string">&quot;http://localhost:8080/ajax-demo/selectUserServlet?username=&quot;</span> + username);</span><br><span class="line">xhttp.<span class="title function_">send</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取响应</span></span><br><span class="line">xhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; <span class="variable language_">this</span>.<span class="property">status</span> == <span class="number">200</span>) &#123;</span><br><span class="line">        <span class="comment">//处理响应的结果</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>处理响应：是否显示提示信息<br>当 <code>this.readyState == 4 &amp;&amp; this.status == 200</code> 条件满足时，说明已经成功响应数据了。<br>此时需要判断响应的数据是否是 “true” 字符串，如果是说明用户名已经占用给出错误提示；如果不是说明用户名未被占用清除错误提示。代码如下</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//判断</span></span><br><span class="line"><span class="keyword">if</span>(<span class="variable language_">this</span>.<span class="property">responseText</span> == <span class="string">&quot;true&quot;</span>)&#123;</span><br><span class="line">    <span class="comment">//用户名存在，显示提示信息</span></span><br><span class="line">    <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;username_err&quot;</span>).<span class="property">style</span>.<span class="property">display</span> = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">&#125;<span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">//用户名不存在 ，清楚提示信息</span></span><br><span class="line">    <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;username_err&quot;</span>).<span class="property">style</span>.<span class="property">display</span> = <span class="string">&#x27;none&#x27;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>综上所述，前端的完整代码如下</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;utf-8&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/ajax_demo/selectUserServlet&quot;</span> <span class="attr">method</span>=<span class="string">&quot;get&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>欢迎注册<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">    用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">id</span>=<span class="string">&quot;username&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span> <span class="attr">id</span>=<span class="string">&quot;username_arr&quot;</span> <span class="attr">style</span>=<span class="string">&quot;display:none;&quot;</span>&gt;</span>用户名已被占用<span class="tag">&lt;/<span class="name">span</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    密码：<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">value</span>=<span class="string">&quot;注册&quot;</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;username&quot;</span>).<span class="property">onblur</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> xhttp;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> username = <span class="variable language_">this</span>.<span class="property">value</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">XMLHttpRequest</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">            xhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span></span><br><span class="line"><span class="language-javascript">        &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// code for IE6, IE5</span></span></span><br><span class="line"><span class="language-javascript">            xhttp = <span class="keyword">new</span> <span class="title class_">ActiveXObject</span>(<span class="string">&quot;Microsoft.XMLHTTP&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//建立连接</span></span></span><br><span class="line"><span class="language-javascript">        xhttp.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, <span class="string">&quot;http://localhost:8080/ajax_demo/selectUserServlet?username=&quot;</span> + username);</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//发送请求</span></span></span><br><span class="line"><span class="language-javascript">        xhttp.<span class="title function_">send</span>();</span></span><br><span class="line"><span class="language-javascript">        xhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; <span class="variable language_">this</span>.<span class="property">status</span> == <span class="number">200</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// 通过 this.responseText 可以获取到服务端响应的数据</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// alert(this.responseText);</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">responseText</span> == <span class="string">&quot;true&quot;</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                    <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;username_arr&quot;</span>).<span class="property">style</span>.<span class="property">display</span> = <span class="string">&#x27;&#x27;</span>;</span></span><br><span class="line"><span class="language-javascript">                &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="language-javascript">                    <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;username_arr&quot;</span>).<span class="property">style</span>.<span class="property">display</span> = <span class="string">&#x27;none&#x27;</span>;</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;;</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-3-4-测试"><a href="#3-3-4-测试" class="headerlink" title="3.3.4.测试"></a>3.3.4.测试</h3><p>重启服务器，访问<code>http://localhost:8080/ajax_demo/register.html</code>，随便输入用户名之后，鼠标点击其他位置失去焦点，会显示<code>用户名已被占用</code></p>
<h1 id="Axios"><a href="#Axios" class="headerlink" title="Axios"></a>Axios</h1><h2 id="4-1基本使用"><a href="#4-1基本使用" class="headerlink" title="4.1基本使用"></a>4.1基本使用</h2><p>​	使用axios 发送请求，并获取响应结果</p>
<p>​			发送 get 请求</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">axios</span>(&#123;</span><br><span class="line">    <span class="attr">method</span>:<span class="string">&quot;get&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>:<span class="string">&quot;http://localhost:8080/ajax-demo1/ajaxDemo?username=zhangsan&quot;</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>)&#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​			发送 post 请求</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">axios</span>(&#123;</span><br><span class="line">    <span class="attr">method</span>:<span class="string">&quot;post&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>:<span class="string">&quot;http://localhost:8080/ajax-demo1/ajaxDemo&quot;</span>,</span><br><span class="line">    <span class="attr">data</span>:<span class="string">&quot;username=zhangsan&quot;</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>)&#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><code>axios()</code> 是用来发送异步请求的，小括号中使用 js 对象传递请求相关的参数：</p>
<ul>
<li><code>method</code> 属性：用来设置请求方式的。取值为 <code>get</code> 或者 <code>post</code>。</li>
<li><code>url</code> 属性：用来书写请求的资源路径。如果是 <code>get</code> 请求，需要将请求参数拼接到路径的后面，格式为： <code>url?参数名=参数值&amp;参数名2=参数值2</code>。</li>
<li><code>data</code> 属性：作为请求体被发送的数据。也就是说如果是 <code>post</code> 请求的话，数据需要作为 <code>data</code> 属性的值。</li>
<li><code>then()</code> 需要传递一个匿名函数。我们将 <code>then()</code> 中传递的匿名函数称为<code>回调函数</code>，意思是该匿名函数在发送请求时不会被调用，而是在成功响应后调用的函数。而该回调函数中的 <code>resp</code> 参数是对响应的数据进行封装的对象，通过 <code>resp.data</code> 可以获取到响应的数据。</li>
</ul>
<h2 id="4-2快速入门"><a href="#4-2快速入门" class="headerlink" title="4.2快速入门"></a>4.2快速入门</h2><h3 id="4-2-1-后端实现"><a href="#4-2-1-后端实现" class="headerlink" title="4.2.1.后端实现"></a>4.2.1.后端实现</h3><p>​			定义一个用于接收请求的servlet，代码如下</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@WebServlet(&quot;/ajaxServlet&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AjaxServlet</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;get...&quot;</span>);</span><br><span class="line">        <span class="comment">//接收请求参数</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">username</span> <span class="operator">=</span> request.getParameter(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        System.out.println(username);</span><br><span class="line">        <span class="comment">//响应数据</span></span><br><span class="line">        response.getWriter().write(<span class="string">&quot;HELLO AXIOS&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doPost</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;post...&quot;</span>);</span><br><span class="line">        <span class="built_in">this</span>.doGet(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-2-2-前端实现"><a href="#4-2-2-前端实现" class="headerlink" title="4.2.2.前端实现"></a>4.2.2.前端实现</h3><p>​			引入 js 文件</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script src=<span class="string">&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;</span>&gt;&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<p>​			发送 ajax 请求</p>
<p>​			get 请求</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">axios</span>(&#123;</span><br><span class="line">    <span class="attr">method</span>: <span class="string">&quot;get&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&quot;http://localhost:8080/ajax_demo/ajaxServlet?username=zhangsan&quot;</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​			post 请求</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">axios</span>(&#123;</span><br><span class="line">    <span class="attr">method</span>: <span class="string">&quot;post&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&quot;http://localhost:8080/ajax_demo/ajaxServlet&quot;</span>,</span><br><span class="line">    <span class="attr">data</span>: <span class="string">&quot;username=zhangsan&quot;</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​		整体页面代码如下</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// axios(&#123;</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//     method: &quot;get&quot;,</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//     url: &quot;http://localhost:8080/ajax_demo/ajaxServlet?username=zhangsan&quot;</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// &#125;).then(function (resp) &#123;</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//     alert(resp.data);</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// &#125;)</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">axios</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="attr">method</span>: <span class="string">&quot;post&quot;</span>,</span></span><br><span class="line"><span class="language-javascript">        <span class="attr">url</span>: <span class="string">&quot;http://localhost:8080/ajax_demo/ajaxServlet&quot;</span>,</span></span><br><span class="line"><span class="language-javascript">        <span class="attr">data</span>: <span class="string">&quot;username=zhangsan&quot;</span></span></span><br><span class="line"><span class="language-javascript">    &#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;)</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​		分别测试get请求和post请求，</p>
<p>​			get请求会在页面上出现一个alert弹窗显示<code>HELLO AXIOS</code>，同时控制台输出</p>
<blockquote>
<p>​	get…</p>
<p>​	zhangsan</p>
</blockquote>
<p>​			post请求会在页面上出现一个alert弹窗显示<code>HELLO AXIOS</code>，同时控制台输出</p>
<blockquote>
<p>​	post…</p>
<p>​	get…</p>
<p>​	zhangsan</p>
</blockquote>
<h2 id="4-3请求方法别名"><a href="#4-3请求方法别名" class="headerlink" title="4.3请求方法别名"></a>4.3请求方法别名</h2><p>​		为了方便起见， Axios 已经为所有支持的请求方法提供了别名。如下：</p>
<ul>
<li><code>get</code> 请求 ： <code>axios.get(url[,config])</code></li>
<li><code>delete</code> 请求 ： <code>axios.delete(url[,config])</code></li>
<li><code>head</code> 请求 ： <code>axios.head(url[,config])</code></li>
<li><code>options</code> 请求 ： <code>axios.option(url[,config])</code></li>
<li><code>post</code> 请求：<code>axios.post(url[,data[,config])</code></li>
<li><code>put</code> 请求：<code>axios.put(url[,data[,config])</code></li>
<li><code>patch</code> 请求：<code>axios.patch(url[,data[,config])</code></li>
</ul>
<p>​		而我们只关注 <code>get</code> 请求和 <code>post</code> 请求。</p>
<p>​	入门案例中的 <code>get</code> 请求代码可以改为如下</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">axios.<span class="title function_">get</span>(<span class="string">&quot;http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan&quot;</span>).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>​	入门案例中的 <code>post</code> 请求代码可以改为如下</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">axios.<span class="title function_">post</span>(<span class="string">&quot;http://localhost:8080/ajax-demo/axiosServlet&quot;</span>,<span class="string">&quot;username=zhangsan&quot;</span>).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>









<h1 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h1><h2 id="5-1概述"><a href="#5-1概述" class="headerlink" title="5.1概述"></a>5.1概述</h2><p>​	概述</p>
<p>​	概念：<code>JavaScript Object Notation</code>。JavaScript 对象表示法.</p>
<p>​	如下是 <code>JavaScript</code> 对象的定义格式：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&quot;zhangsan&quot;</span>,</span><br><span class="line">    <span class="attr">age</span>:<span class="number">23</span>,</span><br><span class="line">    <span class="attr">city</span>:<span class="string">&quot;北京&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	接下来我们再看看 <code>JSON</code> 的格式：</p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">    <span class="attr">&quot;name&quot;</span><span class="punctuation">:</span><span class="string">&quot;zhangsan&quot;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;age&quot;</span><span class="punctuation">:</span><span class="number">23</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;city&quot;</span><span class="punctuation">:</span><span class="string">&quot;北京&quot;</span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br></pre></td></tr></table></figure>

<p>​	通过上面 js 对象格式和 json 格式进行对比，发现两个格式特别像。只不过 js 对象中的属性名可以使用引号（可以是单	引号，也可以是双引号）；而 <code>json</code> 格式中的键要求必须使用双引号括起来，这是 <code>json</code> 格式的规定。<code>json</code> 格式的数据	有什么作用呢？</p>
<p>​	作用：由于其语法格式简单，层次结构鲜明，现多用于作为<code>数据载体</code></p>
<h2 id="5-2JSON基础语法"><a href="#5-2JSON基础语法" class="headerlink" title="5.2JSON基础语法"></a>5.2JSON基础语法</h2><h3 id="5-2-1-定义格式"><a href="#5-2-1-定义格式" class="headerlink" title="5.2.1.定义格式"></a>5.2.1.定义格式</h3><p>​	JSON本质就是一个字符串，但是该字符串内容是有一定的格式要求的。 定义格式如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> 变量名 = &#123;<span class="string">&quot;key&quot;</span>:value,<span class="string">&quot;key&quot;</span>:value,...&#125;;</span><br></pre></td></tr></table></figure>

<p>​		<code>JSON</code>串的键要求必须使用双引号括起来，而值根据要表示的类型确定。value 的数据类型分为如下</p>
<ul>
<li>数字（整数或浮点数）</li>
<li>字符串（使用双引号括起来）</li>
<li>逻辑值（true或者false）</li>
<li>数组（在方括号中）</li>
<li>对象（在花括号中）</li>
<li>null</li>
</ul>
<h3 id="5-2-2-代码演示"><a href="#5-2-2-代码演示" class="headerlink" title="5.2.2.代码演示"></a>5.2.2.代码演示</h3><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">  <span class="keyword">let</span> jsonStr = <span class="string">&#x27;&#123;&quot;name&quot;:&quot;zhangsan&quot;,&quot;age&quot;:18,&quot;addr&quot;:[&quot;北京&quot;,&quot;上海&quot;,&quot;广州&quot;,&quot;深圳&quot;]&#125;&#x27;</span>;</span></span><br><span class="line"><span class="language-javascript">  <span class="title function_">alert</span>(jsonStr);</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​		通过浏览器打开，浏览器会有一个弹窗显示&#96;{“name”:”zhangsan”,”age”:18,”addr”:[“北京”,”上海”,”广州”,”深圳”]}</p>
<p>​		现在我们需要获取到该 <code>JSON</code> 串中的 <code>name</code> 属性值，应该怎么处理呢？</p>
<ul>
<li>如果它是一个 js 对象，我们就可以通过 <code>js对象.属性名</code> 的方式来获取数据。JS 提供了一个对象 <code>JSON</code> ，该对象有如下两个方法：<ul>
<li><code>parse(str)</code> ：将 JSON串转换为 js 对象。使用方式是：<code>var jsObject = JSON.parse(jsonStr);</code></li>
<li><code>stringify(obj)</code> ：将 js 对象转换为 JSON 串。使用方式是：<code>var jsonStr = JSON.stringify(jsObject)</code></li>
</ul>
</li>
</ul>
<p>​			代码演示：</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">let</span> jsonStr = <span class="string">&#x27;&#123;&quot;name&quot;:&quot;zhangsan&quot;,&quot;age&quot;:18,&quot;addr&quot;:[&quot;北京&quot;,&quot;上海&quot;,&quot;广州&quot;,&quot;深圳&quot;]&#125;&#x27;</span>;</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">alert</span>(jsonStr);</span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//将json字符串转化为js对象</span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">let</span> jsonObj = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(jsonStr);</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">alert</span>(jsonObj);</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">alert</span>(jsonObj.<span class="property">name</span>);</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">alert</span>(jsonObj.<span class="property">age</span>);</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">alert</span>(jsonObj.<span class="property">addr</span>);</span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//将js对象转化为json字符串</span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">let</span> jsonStr2 = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(jsonObj);</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">alert</span>(jsonStr2);</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="5-2-3-发送异步请求携带参数"><a href="#5-2-3-发送异步请求携带参数" class="headerlink" title="5.2.3.发送异步请求携带参数"></a>5.2.3.发送异步请求携带参数</h3><p>​	后面我们使用 <code>axios</code> 发送请求时，如果要携带复杂的数据时都会以 <code>JSON</code> 格式进行传递</p>
<p>​	请求参数不可能由我们自己拼接字符串的，我们可以提前定义一个 js 对象，用来封装需要提交的参数，然后使用 <code>JSON.stringify(js对象)</code> 转换为 <code>JSON</code> 串，再将该 <code>JSON</code> 串作为 <code>axios</code> 的 <code>data</code> 属性值进行请求参数的提交。如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> jsObject = &#123;<span class="attr">name</span>:<span class="string">&quot;张三&quot;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="title function_">axios</span>(&#123;</span><br><span class="line">    <span class="attr">method</span>:<span class="string">&quot;post&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>:<span class="string">&quot;http://localhost:8080/ajax-demo/axiosServlet&quot;</span>,</span><br><span class="line">    <span class="attr">data</span>: <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(jsObject)</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​		而 <code>axios</code> 是一个很强大的工具。我们只需要将需要提交的参数封装成 js 对象，并将该 js 对象作为 <code>axios</code> 的 <code>data</code> 属		性值进行，它会自动将 js 对象转换为 <code>JSON</code> 串进行提交。如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> jsObject = &#123;<span class="attr">name</span>:<span class="string">&quot;张三&quot;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="title function_">axios</span>(&#123;</span><br><span class="line">    <span class="attr">method</span>:<span class="string">&quot;post&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>:<span class="string">&quot;http://localhost:8080/ajax-demo/axiosServlet&quot;</span>,</span><br><span class="line">    <span class="attr">data</span>:jsObject  <span class="comment">//这里 axios 会将该js对象转换为 json 串的</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">resp</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(resp.<span class="property">data</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​		</p>
<blockquote>
<p>​		注意</p>
<p>​		js 提供的 <code>JSON</code> 对象我们只需要了解一下即可。因为 <code>axios</code> 会自动对 js 对象和 <code>JSON</code> 串进行转换。<br>​		发送异步请求时，如果请求参数是 <code>JSON</code> 格式，那请求方式必须是 <code>POST</code>。因为 <code>JSON</code> 串需要放在请求体中。</p>
</blockquote>
<h2 id="5-3JSON串和Java对象的相互转换"><a href="#5-3JSON串和Java对象的相互转换" class="headerlink" title="5.3JSON串和Java对象的相互转换"></a>5.3JSON串和Java对象的相互转换</h2><p>​	学习完 json 后，接下来聊聊 json 的作用。以后我们会以 json 格式的数据进行前后端交互。前端发送请求时，如果是复杂的数据就会以 json 提交给后端；而后端如果需要响应一些复杂的数据时，也需要以 json 格式将数据响应回给浏览器。</p>
<p>在后端我们就需要重点学习以下两部分操作：</p>
<ul>
<li>请求数据：JSON字符串转为Java对象</li>
<li>响应数据：Java对象转为JSON字符串</li>
</ul>
<p>阿里提供的一套 API <code>Fastjson</code>，可以帮我们实现上面两部分操作。</p>
<h3 id="5-3-1-Fastjson概述"><a href="#5-3-1-Fastjson概述" class="headerlink" title="5.3.1.Fastjson概述"></a>5.3.1.Fastjson概述</h3><p>​	<code>Fastjson</code> 是阿里巴巴提供的一个Java语言编写的高性能功能完善的 <code>JSON</code> 库，是目前Java语言中最快的 <code>JSON</code> 库，可以实现 <code>Java</code> 对象和 <code>JSON</code> 字符串的相互转换。</p>
<h3 id="5-3-2-Fastjson使用"><a href="#5-3-2-Fastjson使用" class="headerlink" title="5.3.2.Fastjson使用"></a>5.3.2.Fastjson使用</h3><p>​	<code>Fastjson</code> 使用也是比较简单的，分为以下三步完成</p>
<p>​	1.导入坐标</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>fastjson<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.62<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​	2.Java对象转JSON</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">jsonStr</span> <span class="operator">=</span> JSON.toJSONString(obj);</span><br></pre></td></tr></table></figure>

<p>​		将 Java 对象转换为 JSON 串，只需要使用 <code>Fastjson</code> 提供的 <code>JSON</code> 类中的 <code>toJSONString()</code> 静态方法即可。</p>
<p>​	3.JSON字符串转Java对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> JSON.parseObject(jsonStr, User.class);</span><br></pre></td></tr></table></figure>

<p>​		将 json 转换为 Java 对象，只需要使用 <code>Fastjson</code> 提供的 <code>JSON</code> 类中的 <code>parseObject()</code> 静态方法即可。</p>
<h3 id="5-3-3-代码演示"><a href="#5-3-3-代码演示" class="headerlink" title="5.3.3.代码演示"></a>5.3.3.代码演示</h3><p>​		1.先创建一个User类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.blog.web.pojo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">User</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">User</span><span class="params">(Integer id, String username, String password)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.id = id;</span><br><span class="line">        <span class="built_in">this</span>.username = username;</span><br><span class="line">        <span class="built_in">this</span>.password = password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getId</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setId</span><span class="params">(Integer id)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getUsername</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setUsername</span><span class="params">(String username)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.username = username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getPassword</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setPassword</span><span class="params">(String password)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.password = password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;User&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;id=&quot;</span> + id +</span><br><span class="line">                <span class="string">&quot;, username=&#x27;&quot;</span> + username + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, password=&#x27;&quot;</span> + password + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​		2.测试方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSON;</span><br><span class="line"><span class="keyword">import</span> com.blog.web.pojo.User;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FastjsonDemo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//1. 将Java对象转为JSON字符串</span></span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user.setId(<span class="number">1</span>);</span><br><span class="line">        user.setUsername(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">        user.setPassword(<span class="string">&quot;asd123&quot;</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">jsonString</span> <span class="operator">=</span> JSON.toJSONString(user);</span><br><span class="line">        System.out.println(jsonString);</span><br><span class="line">        <span class="comment">//2. 将JSON字符串转为Java对象</span></span><br><span class="line">        <span class="type">User</span> <span class="variable">u</span> <span class="operator">=</span> JSON.parseObject(<span class="string">&quot;&#123;\&quot;id\&quot;:1,\&quot;password\&quot;:\&quot;asd123\&quot;,\&quot;username\&quot;:\&quot;zhangsan\&quot;&#125;&quot;</span>, User.class);</span><br><span class="line">        System.out.println(u);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​		3.得到输出结果如下</p>
<blockquote>
<p>​		{“id”:1,”password”:”asd123”,”username”:”zhangsan”}</p>
<p>​		User{id&#x3D;1, username&#x3D;’zhangsan’, password&#x3D;’asd123’}</p>
</blockquote>
<p><strong>转载来自 <a target="_blank" rel="noopener" href="https://cyborg2077.github.io/">Kyle’s Blog</a>！</strong></p>
<p><strong>文章作者:</strong> <a href="mailto:undefined">Kyle Violet</a></p>
<p><strong>文章链接:</strong> <a target="_blank" rel="noopener" href="https://cyborg2077.github.io/2022/08/21/JavaWeb08/">https://cyborg2077.github.io/2022/08/21/JavaWeb08/</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://aihcola.github.io">AIHCOLA</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://aihcola.github.io/2023/03/05/Filter&amp;Listener&amp;AJAX/">https://aihcola.github.io/2023/03/05/Filter&amp;Listener&amp;AJAX/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://aihcola.github.io" target="_blank">ai_喝可乐's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaWeb/">JavaWeb</a><a class="post-meta__tags" href="/tags/JavaEE/">JavaEE</a><a class="post-meta__tags" href="/tags/Filter/">Filter</a><a class="post-meta__tags" href="/tags/Listener/">Listener</a><a class="post-meta__tags" href="/tags/AJAX/">AJAX</a></div><div class="post_share"><div class="social-share" data-image="https://picsum.photos/seed/d/3456/2304" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/05/05/JDBC/"><img class="prev-cover" src= "" data-lazy-src="https://picsum.photos/seed/d/3456/2304" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JDBC</div></div></a></div><div class="next-post pull-right"><a href="/2022/11/22/%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%96%87%E7%AB%A0/"><img class="next-cover" src= "" data-lazy-src="https://picsum.photos/seed/d/3456/2304" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">第一个文章</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/05/05/JDBC/" title="JDBC"><img class="cover" src= "" data-lazy-src="https://picsum.photos/seed/d/3456/2304" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-05</div><div class="title">JDBC</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Filter"><span class="toc-text">Filter</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-Filter%E6%A6%82%E8%BF%B0"><span class="toc-text">1.1.Filter概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-Filter%E5%85%A5%E9%97%A8"><span class="toc-text">1.2.Filter入门</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-1%E5%BC%80%E5%8F%91%E6%AD%A5%E9%AA%A4"><span class="toc-text">1.2.1开发步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-1%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA"><span class="toc-text">1.2.1代码演示</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-Filter%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="toc-text">1.3.Filter执行流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-4-Filter%E6%8B%A6%E6%88%AA%E8%B7%AF%E5%BE%84%E9%85%8D%E7%BD%AE"><span class="toc-text">1.4.Filter拦截路径配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-5-%E8%BF%87%E6%BB%A4%E5%99%A8%E9%93%BE"><span class="toc-text">1.5.过滤器链</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-1-%E6%A6%82%E8%BF%B0"><span class="toc-text">1.5.1.概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-2-%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA"><span class="toc-text">1.5.2.代码演示</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-3-%E9%97%AE%E9%A2%98"><span class="toc-text">1.5.3.问题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-6-%E6%A1%88%E4%BE%8B"><span class="toc-text">1.6.案例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-1-%E9%9C%80%E6%B1%82"><span class="toc-text">1.6.1.需求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-2-%E5%88%86%E6%9E%90"><span class="toc-text">1.6.2.分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-3-%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-text">1.6.3.代码实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-6-3-1-%E5%88%9B%E5%BB%BAFilter"><span class="toc-text">1.6.3.1.创建Filter</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-6-3-2-%E7%BC%96%E5%86%99%E9%80%BB%E8%BE%91%E4%BB%A3%E7%A0%81"><span class="toc-text">1.6.3.2.编写逻辑代码</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-6-3-3-%E6%B5%8B%E8%AF%95%E5%B9%B6%E6%8A%9B%E5%87%BA%E9%97%AE%E9%A2%98"><span class="toc-text">1.6.3.3.测试并抛出问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-6-3-4-%E9%97%AE%E9%A2%98%E5%88%86%E6%9E%90%E5%8F%8A%E8%A7%A3%E5%86%B3"><span class="toc-text">1.6.3.4.问题分析及解决</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-6-3-5-%E8%BF%87%E6%BB%A4%E5%99%A8%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="toc-text">1.6.3.5.过滤器完整代码</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Listener"><span class="toc-text">Listener</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1%E6%A6%82%E8%BF%B0"><span class="toc-text">2.1概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2%E5%88%86%E7%B1%BB"><span class="toc-text">2.2分类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA"><span class="toc-text">2.3代码演示</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#AJAX"><span class="toc-text">AJAX</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1%E6%A6%82%E8%BF%B0"><span class="toc-text">3.1概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">3.1.1.作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-2-%E5%90%8C%E6%AD%A5%E4%B8%8E%E5%BC%82%E6%AD%A5"><span class="toc-text">3.1.2.同步与异步</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-text">3.2快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-1-%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-text">3.2.1.服务端实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-2-%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-text">3.2.2.客户端实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-3-%E6%B5%8B%E8%AF%95"><span class="toc-text">3.2.3.测试</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-3%E6%A1%88%E4%BE%8B"><span class="toc-text">3.3案例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-1-%E5%88%86%E6%9E%90"><span class="toc-text">3.3.1.分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-2-%E5%90%8E%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-text">3.3.2.后端实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-3-%E5%89%8D%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-text">3.3.3.前端实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-4-%E6%B5%8B%E8%AF%95"><span class="toc-text">3.3.4.测试</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Axios"><span class="toc-text">Axios</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">4.1基本使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-2%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-text">4.2快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-1-%E5%90%8E%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-text">4.2.1.后端实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-2-%E5%89%8D%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-text">4.2.2.前端实现</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-3%E8%AF%B7%E6%B1%82%E6%96%B9%E6%B3%95%E5%88%AB%E5%90%8D"><span class="toc-text">4.3请求方法别名</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JSON"><span class="toc-text">JSON</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#5-1%E6%A6%82%E8%BF%B0"><span class="toc-text">5.1概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-2JSON%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95"><span class="toc-text">5.2JSON基础语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-1-%E5%AE%9A%E4%B9%89%E6%A0%BC%E5%BC%8F"><span class="toc-text">5.2.1.定义格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-2-%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA"><span class="toc-text">5.2.2.代码演示</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-3-%E5%8F%91%E9%80%81%E5%BC%82%E6%AD%A5%E8%AF%B7%E6%B1%82%E6%90%BA%E5%B8%A6%E5%8F%82%E6%95%B0"><span class="toc-text">5.2.3.发送异步请求携带参数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-3JSON%E4%B8%B2%E5%92%8CJava%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%9B%B8%E4%BA%92%E8%BD%AC%E6%8D%A2"><span class="toc-text">5.3JSON串和Java对象的相互转换</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-1-Fastjson%E6%A6%82%E8%BF%B0"><span class="toc-text">5.3.1.Fastjson概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-2-Fastjson%E4%BD%BF%E7%94%A8"><span class="toc-text">5.3.2.Fastjson使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-3-%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA"><span class="toc-text">5.3.3.代码演示</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By AIHCOLA</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>